package com.example.im.ui.activity

import android.view.MenuItem
import android.view.View
import android.widget.MediaController

import com.example.im.R
import com.example.im.mvp.base.BasePresenter
import com.example.im.ui.abstracts.AbstractBaseActivity
import kotlinx.android.synthetic.main.activity_file_browser.*
import kotlinx.android.synthetic.main.include_toolbar.*
import java.io.File

class FileBrowserActivity : AbstractBaseActivity<BasePresenter<*>>() {
    override val layoutId: Int
        get() = R.layout.activity_file_browser

    override fun initView() {

        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        val path = intent.getStringExtra("file_path")
        val fileName = path.substring(path.lastIndexOf("/") + 1)
        tv_toolbar_title.text = fileName
        if (fileName.substring(fileName.indexOf(".")).contains("mp4") ||
            fileName.substring(fileName.indexOf(".")).contains("MP4")
        ) {
            ll_videoView.visibility = View.VISIBLE
            superFileView.visibility = View.GONE
            val mediaController = MediaController(this)
            videoView.setMediaController(mediaController)
            mediaController.setMediaPlayer(videoView)
            videoView.setVideoPath(path)
            videoView.start()
        } else {
            superFileView.visibility = View.VISIBLE
            ll_videoView.visibility = View.GONE
            superFileView.setOnGetFilePathListener {
                it.displayFile(File(path))
            }
            superFileView.setOnGetFileFillListener {
                text_hint.text = "文件暂不支持本地查看，请用其他应用打开\n$path"
            }
            superFileView.show()
        }
    }

    override fun initPresenter() {

    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            android.R.id.home -> {
                finish()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onDestroy() {
        super.onDestroy()
        superFileView.onStopDisplay()
        if (videoView.isPlaying) {
            videoView.pause()
        }
    }
}
